from django.shortcuts import render,redirect,HttpResponse
from .models import *
from django.db.models import Q
from django.core.paginator import Paginator

# Create your views here.
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        truename = request.POST.get('truename')
        pwd = request.POST.get('pwd')
        try:
            user = Doctor.objects.filter(Q(truename=truename) & Q(pwd=pwd)).last()
            if user is not None:
                return redirect('index_pres')
            else:
                return render(request, 'login.html', {"error": '医生名或密码错误'})
        except:
            return render(request, 'login.html',{"error":'医生名或密码错误'})

def index_pres(request):
    cname=request.GET.get('cname','')
    if cname is not None:
        list=Pres.objects.filter(cname__contains=cname)
    else:
        list=Pres.objects.all()
    paginator=Paginator(list,2)
    x = request.GET.get('page', '1')
    try:
        x = int(x)
        if x < 0:
            x = 1
    except Exception as e:
        x = 1
    pagex = paginator.get_page(x)
    return render(request,'index_pres.html',{"pagex":pagex,"cname":cname,'has':pagex.has_next()})

def del_pres(request,id):
    id=Pres.objects.get(id=id)
    id.delete()
    return redirect('index_pres')

def update_pres(request,id):
    if request.method=="GET":
        doc=Doctor.objects.all()
        edit = Pres.objects.get(id=id)
        return render(request,'update_pres.html',{"doc":doc,"edit":edit})
    if request.method=="POST":
        edit=Pres.objects.get(id=id)
        cname = request.POST.get('cname', '')
        result = request.POST.get('result', '')
        hname = request.POST.get('hname', '')
        doctor = request.POST.get('doctor')
        edit.cname=cname
        edit.result=result
        edit.hname=hname
        edit.doctor_id=doctor
        edit.save()
        return redirect('index_pres')

def add_pres(request):
    if request.method=="GET":
        doc=Doctor.objects.all()
        return render(request,'add_pres.html',{"doc":doc})
    if request.method=="POST":
        cname=request.POST.get('cname','')
        result=request.POST.get('result','')
        hname=request.POST.get('hname','')
        doctor=request.POST.get('doctor')
        Pres.objects.create(cname=cname,result=result,hname=hname,doctor_id=doctor)
        return redirect('index_pres')